package com.seven.smartsnmp.utils;

import com.seven.smartsnmp.base.MyException;
import com.seven.smartsnmp.base.MyLog;
import com.seven.smartsnmp.base.OMMappingInfo;
import com.seven.smartsnmp.handler.SelectHandler;
import com.seven.smartsnmp.snmp.SNMPAPI;
import net.percederberg.mibble.MibType;
import net.percederberg.mibble.MibValueSymbol;
import net.percederberg.mibble.snmp.SnmpIndex;
import net.percederberg.mibble.snmp.SnmpObjectType;
import net.percederberg.mibble.value.ObjectIdentifierValue;
import org.apache.commons.lang3.StringUtils;
import org.apache.log4j.Logger;
import org.snmp4j.PDU;
import org.snmp4j.PDUv1;
import org.snmp4j.ScopedPDU;
import org.snmp4j.Snmp;
import org.snmp4j.event.ResponseEvent;
import org.snmp4j.mp.SnmpConstants;
import org.snmp4j.smi.*;

import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.net.InetAddress;
import java.util.ArrayList;
import java.util.List;
import java.util.Vector;

public class SNMPUtils {

    private static final Logger log = Logger.getLogger(SelectHandler.class);

    public SNMPUtils() {
    }

    public static String getMibOIDofClass(Class clazz) throws MyException {
        try {
            Object obj = clazz.newInstance();
            return ((OMMappingInfo) obj).getMappingOID();
        } catch (Exception e) {
            throw new MyException("获取" + clazz + "对应的oid时出错：" + e.getMessage());
        }
    }

    public static void setFieldValue(Object var0, String var1, Variable var2) {
        try {
            String var3 = "set" + var1.replaceFirst(var1.substring(0, 1), var1.substring(0, 1).toUpperCase());
            Class var4 = var0.getClass();
            Field var5 = var4.getDeclaredField(var1);
            if (var5 == null) {
                return;
            }

            Class var6 = var5.getType();
            Method var7 = var4.getMethod(var3, var6);
            String var8 = var6.getName();
            if (var8.equalsIgnoreCase("int")) {
                int var9 = var2.toInt();
                if (var2 instanceof Null) {
                    var9 = 0;
                }

                var7.invoke(var0, new Integer(var9));
            } else if (var8.equalsIgnoreCase("long")) {
                long var12 = var2.toLong();
                if (var2 instanceof Null) {
                    var12 = 0L;
                }

                var7.invoke(var0, new Long(var12));
            } else if (var8.equalsIgnoreCase("java.lang.String")) {
                var7.invoke(var0, var2.toString());
            }
        } catch (Exception var11) {
            MyLog.err("给对象[" + var0.getClass() + "]的属性[" + var1 + "]赋值失败:" + var11.getMessage());
            MyLog.debug(var11);
        }

    }

    public static Variable getFieldValue(Object var0, String var1, MibType var2) {
        try {
            String var3 = "get" + var1.replaceFirst(var1.substring(0, 1), var1.substring(0, 1).toUpperCase());
            Class var4 = var0.getClass();
            Field var5 = var4.getDeclaredField(var1);
            if (var5 == null) {
                return null;
            } else {
                Method var6 = var4.getMethod(var3);
                Object var7 = var6.invoke(var0);
                return getVariable(var2, var7);
            }
        } catch (Exception var8) {
            MyLog.err("给对象[" + var0.getClass() + "]的属性[" + var1 + "]赋值失败:" + var8.getMessage());
            MyLog.debug(var8);
            return new Null();
        }
    }

    public static Variable getVariable(MibType mibType, Object obj) {
        if (mibType.hasTag(0, 2)) {
            Integer32 var12 = new Integer32();
            var12.setValue("" + obj);
            return var12;
        } else if (mibType.hasTag(1, 1)) {
            Counter32 var11 = new Counter32();
            var11.setValue("" + obj);
            return var11;
        } else if (mibType.hasTag(1, 2)) {
            Gauge32 var10 = new Gauge32();
            var10.setValue("" + obj);
            return var10;
        } else if (mibType.hasTag(0, 4)) {
            OctetString var9 = new OctetString();

            try {
                byte[] var3 = ("" + obj).getBytes("utf-8");
                var9 = new OctetString(var3);
            } catch (Exception var4) {
            }

            return var9;
        } else if (mibType.hasTag(0, 6)) {
            OID var8 = new OID("" + obj);
            return var8;
        } else if (mibType.hasTag(1, 0)) {
            IpAddress var7 = new IpAddress("" + obj);
            return var7;
        } else if (mibType.hasTag(1, 3)) {
            TimeTicks var6 = new TimeTicks();
            var6.setValue("" + obj);
            return var6;
        } else if (mibType.hasTag(1, 4)) {
            Opaque var5 = new Opaque(("" + obj).getBytes());
            return var5;
        } else if (mibType.hasTag(1, 6)) {
            Counter64 var2 = new Counter64();
            var2.setValue("" + obj);
            return var2;
        } else {
            MyLog.err("不支持的snmp mib数据类型: " + mibType);
            return new Null();
        }
    }

    public static String getTableOrGroupIndexOID(Object obj, MibValueSymbol mibValueSymbol) throws MyException {
        if (mibValueSymbol.isTableRow()) {
            String mappingOID;
            if (obj instanceof OMMappingInfo) {
                mappingOID = ((OMMappingInfo) obj).getTableIndexOID();
                if (StringUtils.isNoneEmpty(mappingOID)) {
                    return mappingOID;
                }
            } else {
                mappingOID = "";
                ArrayList list = ((SnmpObjectType) mibValueSymbol.getType()).getIndex();

                for (int var4 = 0; var4 < list.size(); ++var4) {
                    SnmpIndex snmpIndex = (SnmpIndex) list.get(var4);
                    ObjectIdentifierValue objectIdentifierValue = (ObjectIdentifierValue) snmpIndex.getValue();
                    String name = objectIdentifierValue.getName();
                    mappingOID = mappingOID + getFieldValue(obj, name, ((SnmpObjectType) objectIdentifierValue.getSymbol().getType()).getSyntax());
                }
            }
            return mappingOID;
        } else {
            return "0";
        }

    }

    public static Vector getFieldsInMibNode(Class var0, MibValueSymbol var1) {
        Field[] var2 = var0.getDeclaredFields();
        Vector var3 = new Vector();

        for (int var4 = 0; var4 < var2.length; ++var4) {
            String var5 = var2[var4].getName();
            MibValueSymbol[] var6 = var1.getChildren();

            for (int var7 = 0; var7 < var6.length; ++var7) {
                if (var6[var7].getName().equals(var5)) {
                    var3.add(var6[var7]);
                    break;
                }
            }
        }

        return var3;
    }

    /**
     * 获取对象字段在mib节点
     *
     * @param clazz
     * @param mibValueSymbol
     * @return
     */
    public static List<MibValueSymbol> getFieldsInMibNodeNew(Class clazz, MibValueSymbol mibValueSymbol) {
        Field[] fields = clazz.getDeclaredFields();
        List<MibValueSymbol> symbolList = new ArrayList<>();
        for (int i = 0; i < fields.length; i++) {
            String fieldName = fields[i].getName();
            MibValueSymbol[] mibValueSymbols = mibValueSymbol.getChildren();
            for (int j = 0; j < mibValueSymbols.length; j++) {
                if (mibValueSymbols[j].getName().equals(fieldName)) {
                    symbolList.add(mibValueSymbols[j]);
                    break;
                }
            }
        }
        return symbolList;
    }

    public static Vector getWritedFieldsInMibNode(Class var0, MibValueSymbol var1) {
        Field[] var2 = var0.getDeclaredFields();
        Vector var3 = new Vector();

        for (int var4 = 0; var4 < var2.length; ++var4) {
            String var5 = var2[var4].getName();
            MibValueSymbol[] var6 = var1.getChildren();

            for (int var7 = 0; var7 < var6.length; ++var7) {
                if (var6[var7].getName().equals(var5)) {
                    SnmpObjectType var8 = (SnmpObjectType) var6[var7].getType();
                    if (var8.getAccess().canWrite()) {
                        var3.add(var6[var7]);
                        break;
                    }
                }
            }
        }

        return var3;
    }

    public static void checkSNMPErro(ResponseEvent var0) throws MyException {
        if (var0.getError() != null) {
            throw new MyException(var0.getError());
        } else {
            PDU var1 = var0.getResponse();
            if (var1 == null) {
                throw new MyException(SNMPAPI.MessageSNMPTimeOut);
            } else if (var1.getErrorStatus() != 0) {
                if (var1.getErrorStatus() == 2) {
                    throw new MyException(SNMPAPI.MessageNoSuchOID);
                } else {
                    throw new MyException(var1.getErrorStatusText());
                }
            } else {
                VariableBinding var2 = var1.get(0);
                if (var2 == null) {
                    throw new MyException(SNMPAPI.MessageSNMPTimeOut);
                } else {
                    Vector var3 = var1.getVariableBindings();
                    if (var3.size() <= 0) {
                        throw new MyException(SNMPAPI.MessageSNMPTimeOut);
                    }
                }
            }
        }
    }

    /**
     * 格式化mac地址
     *
     * @param macAddr
     * @return
     */
    public static String formatDispayMacAddress(String macAddr) {
        String addr = "";
        if (macAddr != null && !macAddr.equals("") && !macAddr.equalsIgnoreCase("null")) {
            try {
                OctetString octetString = new OctetString(macAddr.getBytes("utf-8"));
                addr = octetString.toHexString();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return addr;
    }

    public static String formatCNString(String str) {
        String reStr = "";
        if (str != null && !str.equals("") && !str.equalsIgnoreCase("null")) {
            try {
                reStr = new String(str.getBytes("iso8859_1"), "utf-8");
                return reStr;
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return reStr;
    }

    public static boolean canPing(String ip) {
        try {
            InetAddress var1 = InetAddress.getByName(ip);
            return var1.isReachable(30);
        } catch (Exception e) {
            System.out.println("设备 " + ip + ":无法到达----");
            MyLog.err("isReachable ping host:" + ip + ",erro:" + e.getMessage());
            return false;
        }
    }

    /**
     * 关闭流的通用方法
     *
     * @param snmp
     */
    public static void closeSnmp(Snmp snmp) {
        try {
            if (snmp != null) {
                snmp.close();
            }
        } catch (Exception e) {
            log.error("关闭snmp失败", e);
        }
    }


    public static PDU createPdu(int version) {
        PDU pdu = null;
        if (version == SnmpConstants.version3) {
            pdu = new ScopedPDU();
        } else {
            pdu = new PDUv1();
        }
        return pdu;
    }

}
